package com.amigo.online.provider.adv.quartz.job;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;

import com.amigo.online.common.param.adv.bo.AdvHomeInitBO;
import com.amigo.online.provider.adv.common.ConstantValue;
import com.amigo.online.provider.adv.service.AdvHomeApplyService;
import com.amigo.online.provider.adv.service.AdvHomeStockService;
import com.amigo.online.provider.adv.util.AdvBasicUtil;

/**
 * 初始化首页广告资源
 * 投放的区域
 * 目标用户性别， 年龄
 * 资源库存
 * 资源的组合值是否为 6
 *
 * @author Administrator
 */

@Component
@EnableScheduling
public class InitHomeAdvStockJob extends AbstractInitAdvStockJob implements Job {

    @Autowired
    AdvHomeApplyService advHomeApplyService;

    @Autowired
    AdvHomeStockService advHomeStockService;

    @SuppressWarnings("unchecked")
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        logger.info("--初始化首页--");
        long tomorrow = AdvBasicUtil.getTomorrowZeroPointTimeStamps();
        List<AdvHomeInitBO> deliverPlanList = advHomeApplyService
                .listFindTomorrowAdvDeliveryPlanByStartTime(tomorrow);
        // 根据当前时间戳获取今天的可投放资源
        // List<AdvHomeInitBO> resultList =
        // advHomeApplyService.listFindTodayUsableResourceByTime(currentMillis);
        Map<String, Set<String>> initListMap = new HashMap<>(deliverPlanList.size() * ConstantValue.ADV_AREA_SIZE);
        Map<Long, Integer> initStockMap = new HashMap<>(deliverPlanList.size());
        Map<String, String> initTypeMap = new HashMap<>();
        // 资源入缓存
        for (AdvHomeInitBO temp : deliverPlanList) {
            // 广告资源队列缓存入库，广告资源库存入库
            List<Integer> sexList = new ArrayList<>();
            int sexType = temp.getSexType();
            if (sexType == 0) {
                sexList.add(0);
                sexList.add(1);
                sexList.add(2);
            } else {
                sexList.add(sexType);
            }
            List<Integer> ageList = new ArrayList<>();
            int ageType = temp.getAgeType();
            AdvBasicUtil.tansferAgeTypeToList(ageType, ageList);
            // 地区，性别，年龄三个维度组合做投放队列
            for (Integer sex : sexList) {
                for (Integer age : ageList) {
                    int sexValue = sex;
                    int ageValue = age;
                    if (sex == 0 || age == 0) {
                        sexValue = ageValue = 0;
                    }
                    if (temp.getAreaType() == 2) {
                        for (Integer areaId : temp.getAreaList()) {
                            AbstractSettleAdvStockJob.complexRedisInitMap(ConstantValue.ADV_HOME_LIST, areaId, sexValue, ageValue, initListMap, temp.getId());
                        }
                    } else if (temp.getAreaType() == 1) {
                        // 全国
                        AbstractSettleAdvStockJob.complexRedisInitMap(ConstantValue.ADV_HOME_LIST, 0, sexValue, ageValue, initListMap, temp.getId());
                    } else if (temp.getAreaType() == 3) {
                        // mongo
                    }
                }
            }
            initStockMap.put(temp.getId(), temp.getRemainingNumber());
            initTypeMap.put(String.valueOf(temp.getId()), String.valueOf(temp.getShowType()));
            //complexRedisInitTypeMap(ConstantValue.ADV_HOME_TYPE_LIST, initTypeListMap, temp.getId(), temp.getShowType());
        }

        // 管道操作，减少网络交互
        List<Object> results = stringRedisTemplate.executePipelined(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                StringRedisConnection redisConn = (StringRedisConnection) connection;
                for (String key : initListMap.keySet()) {
                    String[] array = initListMap.get(key).toArray(new String[initListMap.get(key).size()]);
                    redisConn.lPush(key, array);
                }
                for (String key : initTypeMap.keySet()) {
                    redisConn.hSet(ConstantValue.ADV_HOME_TYPE_MAP, key, initTypeMap.get(key));
                }
                return null;
            }
        });
        if (results.size() != initListMap.size()) {
            logger.error("----------------------");
        }
        redisTemplate.opsForHash().putAll(ConstantValue.ADV_HOME_STOCK, initStockMap);

    }

    protected static void complexRedisInitTypeMap(String basicKey, Map<String, Set<String>> initListMap, Long id, int showType) {
        String redisKey = basicKey + showType;
        Set<String> tempSet = initListMap.get(redisKey);
        if (tempSet != null) {
            tempSet.add(String.valueOf(id));
        } else {
            tempSet = new HashSet<>();
            tempSet.add(String.valueOf(id));
            initListMap.put(redisKey, tempSet);
        }
    }

}
